package hip.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.SQLException;


import org.apache.log4j.Logger;



public class Blob2Byte {
	public static Logger logger = Logger.getLogger(Blob2Byte.class);
	/** 
     * 将blob转化为byte[],只对纯文本的有效 
     * 
     * @param blob Oracle数据库中BLOB类型的字段
     * @return Java字节数组
     */  
    public static byte[] getBytes(Blob blob) {
        try {  
            InputStream ins = blob.getBinaryStream();  
            byte[] b = new byte[1024];  
            int num = 0;  
            StringBuilder res = new StringBuilder();
            while ((num = ins.read(b)) != -1) {  
                res.append(new String(b, 0, num));
            }  
            return res.toString().getBytes();
        } catch (SQLException | IOException e) {
            e.printStackTrace();  
        }
        return null;  
    }  
	/** 
     * 将blob转化为String,只对纯文本的有效 
     * 
     * @param blob Oracle数据库中BLOB类型的字段 
     * @return Java字符串
     */  
    public static String getString(Blob blob) {
        try {  
            InputStream ins = blob.getBinaryStream();  
            byte[] b = new byte[1024];  
            int num = 0;  
            StringBuilder res = new StringBuilder();
            while ((num = ins.read(b)) != -1) {  
                res.append(new String(b, 0, num));
            }  
            return res.toString();
        } catch (SQLException | IOException e) {
            e.printStackTrace();  
        }
        return null;  
    }
    
    @SuppressWarnings("unused")
	public static String getString(Blob blob,String charset) {
		StringBuilder sb = new StringBuilder();

		try {
			InputStream in = blob.getBinaryStream();
			byte[] buff = new byte[(int) blob.length()];
			int i = 0;
			while (in.read(buff) != -1) {
				sb.append(new String(buff, charset));
			}
			in.close();
		} catch (Exception e) {
			logger.error("转换BLOB出错！");
			e.printStackTrace();
		}

		return sb.toString();
	}
      
    /** 
     * 将blob转化为byte[],可以转化二进制流的
     * 
     * @param blob Oracle数据库中BLOB类型的字段
     * @return Java字节数组
     */  
    public static byte[] blobToBytes(Blob blob) {
        InputStream is = null;  
        byte[] b = null;  
        try {  
            is = blob.getBinaryStream();  
            b = new byte[(int) blob.length()];  
            is.read(b);  
            return b;  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {
                assert is != null;
                is.close();
            } catch (IOException e) {
                e.printStackTrace();  
            }  
        }  
        return b;  
    }  
}
